/*
 * FrameQueue.cpp
 *
 *  Created on: 2016年3月17日
 *      Author: terry
 */

#include "FrameQueue.h"

namespace av
{

FrameQueue::FrameQueue()
{
}

FrameQueue::~FrameQueue()
{
	clear();
}

size_t FrameQueue::push(AVFramePtr& frame)
{
	comn::AutoCritSec lock(m_cs);
	m_frames.push_back(frame);
	return m_frames.size();
}

AVFramePtr FrameQueue::pop()
{
	comn::AutoCritSec lock(m_cs);
	AVFramePtr frame;
	if (!m_frames.empty())
	{
		frame = m_frames.front();
		m_frames.pop_front();
	}
	return frame;
}

size_t FrameQueue::size()
{
	comn::AutoCritSec lock(m_cs);
	return m_frames.size();
}

void FrameQueue::clear()
{
	comn::AutoCritSec lock(m_cs);
	while (!m_frames.empty())
	{
		AVFramePtr frame = m_frames.front();
		m_frames.pop_front();
	}
}

size_t FrameQueue::popUntil(int64_t pts)
{
	size_t count = 0;
	comn::AutoCritSec lock(m_cs);
	while (!m_frames.empty())
	{
		AVFramePtr frame = m_frames.front();
		int64_t framePts = (frame->pts == AV_NOPTS_VALUE) ? frame->pkt_pts : frame->pts;
		if (framePts <= pts)
		{
			m_frames.pop_front();
			count ++;
		}
		else
		{
			break;
		}
	}
	return count;
}

size_t FrameQueue::popUntilSize(size_t size)
{
	size_t count = 0;
	comn::AutoCritSec lock(m_cs);
	while (m_frames.size() > size)
	{
		m_frames.pop_front();
		count ++;
	}
	return count;
}



} /* namespace av */
